import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
type removeType = 'other' | 'right' | 'index'

const useTagStore = defineStore(
  'tags',
  () => {
    const tagsViewList = ref<TagType[]>([])

    const addTagsViewList = (tag: TagType) => {
      const isFind = tagsViewList.value.find((item) => item.path === tag.path)
      if (!isFind) {
        tag.title = generateTitle(tag)
        tagsViewList.value.push(tag)
      }
    }

    const clearTags = () => {
      tagsViewList.value = []
    }

    /**
     * 删除tag
     * type: 'other' || 'right' || 'index' ;
     * index：下标
     */
    const removeTagsView = (type: removeType, index: number) => {
      switch (type) {
        case 'index':
          // 删除当前
          tagsViewList.value.splice(index, 1)
          break
        case 'other':
          // 删除其他
          tagsViewList.value.splice(index + 1, tagsViewList.value.length - index + 1)
          tagsViewList.value.splice(0, index)
          break
        case 'right':
          // 删除右边
          tagsViewList.value.splice(index + 1, tagsViewList.value.length - index + 1)
          break
      }
    }

    // 删除当前
    const route = useRoute()
    const removeSelf = () => {
      console.log(route.path)
      const index = tagsViewList.value.findIndex((item) => item.path === route.path)
      console.log(index)
      removeTagsView('index', index)
    }

    return { removeSelf, removeTagsView, addTagsViewList, clearTags, tagsViewList }
  },
  {
    persist: {
      storage: sessionStorage
    }
  }
)

function generateTitle(tag: TagType) {
  let res = tag.meta.title

  if (res === 'custom') {
    res = tag.query.title
  }
  return res
}

export default useTagStore
